package com.dhcc.bpm.modules.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.FileUtils;
import com.dhcc.bpm.common.utils.OpenapiGeneratorUtils;
import com.dhcc.bpm.common.utils.StringUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @ClassName DocDirectoryController
 * @Description  公共模块表 控制器
 * @Author xiafayu
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@RestController
@AllArgsConstructor
@NoArgsConstructor
@RequestMapping("bpm-common/shell")
@Api(value = "Shell公共模块表", tags = "Shell公共模块表接口")
public class ShellController extends BladeController {
	private static final Logger log = LoggerFactory.getLogger(ShellController.class);

	@Autowired
	private OpenapiGeneratorUtils openapiGeneratorUtils;

	/**
	 * @return
	 */
	@PostMapping("/shelllog")
	public R<JSONObject> shellLog(@RequestBody JSONObject data) {

		try {
			String logFile = data.getString("logFile");
			int startNum = data.getInteger("startNum")+1;
			logFile = StringUtils.replace(logFile);

			String end =  openapiGeneratorUtils.execCmd("cd "+openapiGeneratorUtils.getPath()+"/log&&sed -n '$=' "+logFile);
			int endNum = Integer.parseInt(end.replaceAll("\n",""));

			String msg =  openapiGeneratorUtils.execCmd("cd "+openapiGeneratorUtils.getPath()+"/log&&sed -n '"+startNum+","+endNum+"p' "+logFile);

			JSONObject result = new JSONObject();
			result.put("endNum",endNum);
			result.put("msg",msg);
			result.put("result",false);
			if(msg.contains("success ok")){
				result.put("result",true);
			}
			return R.data(result);
		}catch (Exception e){
			log.error("shell 日志打印出现错误",e);
			return R.fail(e.getMessage());
		}

	}

	/**
	 * @author: zhangzexu
	 * @date: 2020/08/19 10:35
	 * @description: log文件下载
	 * @param: [filePath, response]
	 * @return: org.springblade.core.tool.api.R
	 */
	@ApiLog("文件下载")
	@GetMapping("/logDownload")
	@Log(title = "cmd执行日志文件下载", businessType = BusinessType.DOWNLOAD)
	public R logDownload(@RequestParam String filePath, HttpServletResponse response){
		filePath = StringUtils.downLoadReplace(filePath);
		File file = new File(openapiGeneratorUtils.getPath()+"/log/"+filePath);
		if(!file.exists()){
			return R.fail("文件不存在");
		}
		if(FileUtils.downloadFile(openapiGeneratorUtils.getPath()+"/log/"+filePath,response)){
			return R.status(true);
		}else {
			return R.fail("文件不存在");
		}

	}


}
